package cn.nextProject.service;

import cn.nextProject.Utils.AESUtils;
import cn.nextProject.Utils.JWTUtils;
import cn.nextProject.entity.User;
import cn.nextProject.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    public Map<String,Object> login(User user) throws SQLException, IOException {

        Map<String,Object> map = new HashMap<>();

        User user1 = userService.getUserByUsernameHasPass(user.getUsername());

        if (ObjectUtils.isEmpty(user1)){
            map.put("state",false);
            map.put("msg","用户名不存在");
            return map;
        }

        if (user1.getState() == 0){
            map.put("state",false);
            map.put("msg","用户已被禁用");
            return map;
        }

        byte[] userKey = user1.getUserKey();

        String password = user1.getUserPassword();
        if (ObjectUtils.isEmpty(userKey) || ObjectUtils.isEmpty(password)){
            map.put("state",false);
            map.put("msg","密钥或密码不存在");
            return map;
        }

        SecretKey secretKey = new SecretKeySpec(userKey, "AES");

        //解密密码
        try {
            String decryptPassword = AESUtils.decryptPassword(password, secretKey);
            if (!decryptPassword.equals(user.getUserPassword())){
                map.put("state",false);
                map.put("msg","密码错误");
                return map;
            }else{ // 密码正确
                //生成JWT令牌
                Map<String, String> payload = new HashMap<>();
                payload.put("username", user1.getUsername());
                payload.put("realname", user1.getRealname());
                String token = JWTUtils.getToken(payload);
                map.put("state",true);
                map.put("msg","认证成功！");
                map.put("token",token);
                user1.setUserKey(null);
                user1.setUserPassword(null);
                map.put("user",user1);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state",false);
            map.put("msg",e);
            return map;
        }

    }

    /**
     * 注册
     * @param user
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public Map<Integer, String> register(User user){

        Map<Integer, String> map = new HashMap<>();
        SecretKey secretKey = null;
        try {
            secretKey = AESUtils.generateAESKey();
        } catch (Exception e) {
            log.error("生成密钥失败:[]",e);
            throw new RuntimeException(e);
        }
        String realPassword = null;

        if (ObjectUtils.isEmpty(secretKey)){
            map.put(0,"生成密钥失败!");
            return map;
        }

        try {
            realPassword = AESUtils.encryptPassword(user.getUserPassword(), secretKey);
        } catch (Exception e) {
            log.error("密码加密失败:[]",e);
            throw new RuntimeException(e);
        }

        if (ObjectUtils.isEmpty(realPassword)){
            map.put(0,"密码加密失败!");
            return map;
        }

        user.setUserKey(secretKey.getEncoded());
        user.setUserPassword(realPassword);
        user.setCreateTime(new Date());

        userService.save(user);

        map.put(1,"注册成功!");
        return map;

    }

}
